package com.faithbj.device.web.controller.admin;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faithbj.device.model.configuration.Pager;
import com.faithbj.device.model.dto.ReservedMember;
import com.faithbj.device.model.entity.DeviceInfo;
import com.faithbj.device.model.entity.Members;
import com.faithbj.device.model.entity.Reservation;
import com.faithbj.device.service.DeviceInfoService;
import com.faithbj.device.service.MailService;
import com.faithbj.device.service.ReservationService;
import com.faithbj.device.utils.DateUtils;

/**
 * @author yfxue
 * 
 * @version 0.1
 * 
 * <br/>
 *          创建时间：2012-5-22
 * 
 * <br/>
 *          类说明：仪器预约
 */
@Controller
@RequestMapping("/faith/reserve")
public class AdminReservationController extends BaseAdminController implements
		Serializable {

	private static final long serialVersionUID = 4811880763669145009L;

	@Resource(name = "reservationService")
	private ReservationService seservationService;

	@Resource(name = "mailService")
	private MailService mailService;

	@Resource(name = "deviceInfoService")
	private DeviceInfoService deviceInfoService;

	@RequestMapping(value = "/menu", method = RequestMethod.GET)
	public String menu() {
		return "admin/menu_reservation";
	}

	@RequestMapping(value = "/list")
	public String list() {
		ModelMap map = new ModelMap();
		Pager pagerVal = seservationService.findByPager(pager);
		map.put("pager", pagerVal);
		return "admin/reservation_list";
	}

	/**
	 * 预约仪器展示页面
	 * @param id
	 * @param map
	 * @return
	 */
	// @RequestMapping(value =
	// "/reserveview/{id}",produces="text/html;charset=UTF-8")
	@RequestMapping(value = "/reserveview/{id}")
	public String reserveview(@PathVariable("id") String id, ModelMap map) {
		DeviceInfo deviceInfo = deviceInfoService.get(id);
		String maxDateStr = DateUtils.getDaysAfter(
				systemConfigUtil.getAllowReservationDay(), "yyyy-MM-dd");

		map.put("deviceInfo", deviceInfo);
		map.put("minDate", DateUtils.getCurrentDateString("yyyy-MM-dd"));
		map.put("maxDate", maxDateStr);

		return "admin/reservation_input";
	}

	@RequestMapping(value = "/appointmentTime",produces="application/json;charset=UTF-8",method = RequestMethod.POST)
	public @ResponseBody ModelMap appointmentTime(Date date, String id) {
		ModelMap map=new ModelMap();
		
		List<String> back = new ArrayList<String>();
		Integer week = DateUtils.getWeekOfDate(date);
		Integer restDay = systemConfigUtil.getRestDaysOfWeek().get(week);
		if (restDay == null) {// 不是休息日
			for (int i = 0; i < 24; i++)
				if (systemConfigUtil.getRestHoursOfDay().get(i) == null)
					back.add("content_qyyy_green");
				else
					back.add("content_qyyy_gray");
		}
		else {
			for (int i = 0; i < 24; i++) {
				back.add("content_qyyy_gray");
			}
			map.put("back", back);
			return map;
		}

		List<Reservation> list = seservationService.findReservationByDeviceId(
				date, id);

		Set<ReservedMember>  resevedmembers=new HashSet<ReservedMember>();//今天预约的人员名单
		
		for (Reservation reservation : list) {
			int beginHour = DateUtils.getHourOfDay(reservation.getBeginDate()
					.getTime() > date.getTime() ? reservation.getBeginDate()
					: date);
			int endHour = DateUtils.getHourOfDay(reservation.getEndDate())-1;
			for (int i = 0; i < 24; i++) {
				if (i >= beginHour && i <= endHour) {
					back.set(i, "content_qyyy_red");
					
					ReservedMember rm=new ReservedMember();
					rm.setUsername(reservation.getMember().getUsername());
					rm.setRealName(reservation.getMember().getRealName());
					rm.setTelephone(reservation.getMember().getTelephone());
					rm.setEmail(reservation.getMember().getEmail());
					rm.setBeginDate(DateUtils.formateDate2String("HH", reservation.getBeginDate()));
					rm.setEndDate(DateUtils.formateDate2String("HH", reservation.getEndDate()));
					resevedmembers.add(rm);
				}
			}
		}
		
		map.put("back", back);
		map.put("members", resevedmembers);
		
		return map;
	}

	@RequestMapping(value = "/reserve")
	public String reserve(Reservation reservation, ModelMap map) {
		String deviceid = reservation.getDevice().getId();
//		Date now = DateUtils.getCurrentBeginDate();
		Date now = new Date();
		
		//不准约过去的时间
		if(reservation.getBeginDate().getTime()<now.getTime()||reservation.getEndDate().getTime()<now.getTime())
		{
			map.put("redirectUrl", "faith/reserve/reserveview/" + deviceid);
			map.put("errorMessages", "不准约已经过去的时间，请预约其他时间段！");
			return ERROR;
		}
		
		//别人已经约定的时间不能约
		List<Reservation> list = seservationService.findReservationByDeviceId(now, deviceid);
		for (Reservation temt : list) {
			boolean fresult = temt.getBeginDate().getTime() > reservation
					.getBeginDate().getTime()
					&& temt.getBeginDate().getTime() < reservation.getEndDate()
							.getTime();
			boolean sresult = temt.getBeginDate().getTime() < reservation
					.getBeginDate().getTime()
					&& temt.getEndDate().getTime() > reservation.getBeginDate()
							.getTime();
			if (fresult || sresult) {
				map.put("redirectUrl", "faith/reserve/reserveview/" + deviceid);
				map.put("errorMessages", "此时间段有人预约，请预约其他时间段！");
				return ERROR;
			}
		}
		
		//约同一个小时,结束小时加一
		if(reservation.getBeginDate().getTime()==reservation.getEndDate().getTime())
		{
			reservation.setEndDate(DateUtils.getHoursAfter(reservation.getEndDate(), 1));
		}
		

		DeviceInfo device = deviceInfoService.get(deviceid);

		calcCost(reservation, device);// 计算费用

		Members members = getLoginMember();

		/*
		 * DeviceInfo reserved=deviceInfoService.get(deviceid); String
		 * text="尊敬的"+members.getUsername()+",您已在"+DateUtils.formateDate2String(
		 * "yyyy-MM-dd HH:mm:ss", reservation.getBeginDate())+"预约了"+
		 * reserved.getLocation()+"的"+reserved.getPropertyName()+",请准时参加！谢谢！";
		 * mailService.sendEmail(members.getEmail(), subject, text);
		 */

		reservation.setMember(members);

		reservation.setChargeStatus(Reservation.UNCHARGED);
		
		
		seservationService.save(reservation);
		map.put("redirectUrl", "faith/reserve/reservelist");
		return SUCCESS;
	}

	@RequestMapping(value = "/reservelist")
	public String reservelist(Pager pager, ModelMap map) {
		Members member = getLoginMember();
		Pager pagerVal = seservationService.findReservationByMemberId(pager,
				member);
		map.put("pager", pagerVal);
		return "admin/reserved_list";
	}

	@RequestMapping(value = "/delete/{id}")
	public String delete(@PathVariable("id") String id, ModelMap map) {
		Date now=new Date();
		
		Reservation deleting=seservationService.get(id);
		if(deleting.getBeginDate().getTime()<now.getTime())
		{
			map.put("errorMessages", "不准取消过去预约的时间，请确认后再操作！");
			return ERROR;
		}
		seservationService.delete(id);
		map.put("redirectUrl", "/faith/reserve/reservelist");
		return SUCCESS;
	}

	/**
	 * 费用结算
	 * 
	 * @param pager
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/costlist")
	public String costlist(Pager pager, ModelMap map) {
		Pager pagerVal = seservationService.findReservationCost(pager);
		map.put("pager", pagerVal);
		return "/admin/cost_list";
	}

	/**
	 * 费用结算查询
	 * 
	 * @param pager
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/costsearch", method = RequestMethod.POST)
	public String reservelist(Reservation reservation,Integer pageNumber, Integer pageSize,
			ModelMap map) {
		Pager pagerVal = seservationService.findReserveCostByExample(
				reservation, pageNumber, pageSize);
		map.put("pager", pagerVal);
		map.put("reservation", reservation);
		return "/admin/cost_list";
	}

	/**
	 * 费用结算编辑页面
	 * 
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/costedit/{id}")
	public String costEdit(@PathVariable("id") String id, ModelMap map) {
		Reservation reservation = seservationService.get(id);
		map.put("reservation", reservation);
		map.put("isAddAction", false);
		return "/admin/cost_input";
	}

	/**
	 * 费用编辑更新
	 * 
	 * @param id
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/costupdate", method = RequestMethod.POST)
	public String costUpdate(Reservation reservation, ModelMap map) {
		Reservation tr = seservationService.get(reservation.getId());
		tr.setRevenue(reservation.getRevenue());
		tr.setChargeStatus(reservation.getChargeStatus());
		seservationService.update(tr);

		map.put("redirectUrl", "/faith/reserve/costlist");
		return SUCCESS;
	}

	/**
	 * 计算仪器的费用
	 */
	public void calcCost(Reservation reservation, DeviceInfo device) {
		if (reservation.getCostType() == Reservation.TIME_COST
				&& device.getTimeCost() != null) {
			Integer calced = DateUtils.betweenHours(reservation.getBeginDate(),
					reservation.getEndDate());
			reservation.setBudget(calced * device.getTimeCost());
		}
		if (reservation.getCostType() == Reservation.COUNT_COST
				&& device.getCountCost() != null) {
			reservation.setBudget(reservation.getSampleCount()
					* device.getCountCost());
		}
	}

}
